﻿@model NB.MGJ.Model.AntiFleeing_Distributor
@using NB.MGJ.Common.Helper;
@{
    Layout = null;
}
<script src="~/Scripts/Bootstrap/js/bootstrap-select.js" charset="utf-8" type="text/javascript"></script>
<link href="~/Scripts/Bootstrap/css/bootstrap-select.min.css" rel="stylesheet" />

@*经销商信息*@
<style>
    #picker{
        position: relative;
    }

    #picker .webuploader-pick{
        display: block;
        width: 91px;
        height: 91px;
    }

    #picker input[type='file']{
        opacity: 0;
        display: block;
        width: 91px;
        height: 91px;
        position: absolute;
        z-index: 99;
    }
</style>
<form id="form" class="form-horizontal" onkeydown="if(event.keyCode==13){return false;}">
    <input hidden name="Id" value="@Model.Id" />
    <div class="form-group">
        <label class="col-sm-2 control-label"><span class="red-600">*</span>经销商名称：</label>
        <div class="col-sm-4">
            @Html.TextBoxFor(p => p.Name, new { @class = "form-control", @placeholder = "请输入经销商名称", maxlength = 25, })
        </div>
        <label class="col-sm-2 control-label">所属片区：</label>
        <div class="col-sm-4">
            @Html.DropDownList("SaleAreaId", null, new { @class = "form-control", @Name = "SalesAreaID", @onchange = " Distributor(" + @Model.ParentId + ")" })
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label">上级经销商：</label>
        <div class="col-sm-4">
            <select id="ParentId" class="form-control" name="ParentId" data-live-search="true" data-actions-box="true" onchange="OnChanges()"></select>
        </div>
        <label class="col-sm-2 control-label"><span class="red-600">*</span>经销商级别：</label>
        <div class="col-sm-4">
            @*@Html.DropDownList("LevelID", null, new { @class = "form-control", @Name = "LevelID" })*@
            <select id="LevelID" class="form-control" name="LevelID" data-live-search="true" data-actions-box="true"></select>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label"><span class="red-600">*</span>管辖区域：</label>
        <div class="col-sm-4">
            <select id="JurisdictionPrivance"  class="form-control" data-live-search="true" data-live-search-placeholder="Search" data-dropup-auto="false" data-actions-box="true" onchange="isSelectAll(); Choose(this.id, 'JurisdictionCity', '0', '1', '0')" title="请选择省"></select>
        </div>
        <div class="col-sm-3" id="csdivid">
            <select id="JurisdictionCity"  class="form-control " data-live-search="true" data-live-search-placeholder="Search" data-dropup-auto="false" data-actions-box="true" onchange="Choose(this.id, 'JurisdictionRegion', '0', '2', '0')" title="请选择市"></select>
        </div>
        <div class="col-sm-3">
            <select id="JurisdictionRegion"  class="form-control " style="color: white" data-live-search="true" data-dropup-auto="false" data-live-search-placeholder="Search" data-actions-box="true" title="请选择区"></select>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label">是否跨区：</label>
        <div class="col-sm-4">
            <input id="f" type="radio" name="IsCrossArea" value="0" checked />
            <label for="f">否</label>
            <input id="y" type="radio" name="IsCrossArea" value="1" />
            <label for="y">是</label>
        </div>
    </div>
    <div class="form-group" id="cross">
        <label class="col-sm-2 control-label">跨区管辖区域：</label>
        <div class="col-sm-4">
            @*@Html.DropDownList("privance", ViewBag.privance as SelectList, new { onchange = "Choose('AcrossPrivance', 'AcrossCity')", @id = "AcrossPrivance", @class = "form-control selectpicker show-tick bs-select", @multiple = "multiple", datalivesearch = "false", @datasize = "6", @title="请选择省" })*@
            <select  id="AcrossPrivance" class="form-control " style="color:white" data-dropup-auto="false" data-live-search="true" data-live-search-placeholder="Search" data-actions-box="true" title="请选择省" onchange="Choose('AcrossPrivance', 'AcrossCity', '0', '1', '1')">
                <option selected>请选择省</option>
            </select>
        </div>
        <div class="col-sm-3">
            <select id="AcrossCity" class="form-control " data-live-search="true" data-dropup-auto="false" data-live-search-placeholder="Search" data-actions-box="true" onchange="Choose(this.id, 'AcrossRegion', '0', '2', '1')" title="请选择市">
                <option selected>请选择市区</option>
            </select>
        </div>
        <div class="col-sm-3">
            @*@Html.DropDownListFor(p => p.AcrossRegion, Html.GetPriCityList(), new { @class = "form-control" })*@
            <select id="AcrossRegion" class="form-control " data-live-search="true" data-dropup-auto="false" data-live-search-placeholder="Search" data-actions-box="true" title="请选择县区">
                <option selected>请选择县区</option>
            </select>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label">所在地：</label>
        <div class="col-sm-4">

            <select id="Province" name="Province" class="form-control " title="请选择省" onchange="Choose1('Province', 'City','0')">
                <option selected>请选择省</option>
            </select>
        </div>
        <div class="col-sm-3">
            <select id="City" class="form-control " name="City" onchange="Choose1(this.id, 'Region','0')" title="请选择市">
                <option selected>请选择市区</option>
            </select>
            @*@Html.DropDownListFor(p => p.City, Html.GetPriCityList(), new { @class = "form-control" })*@
        </div>
        <div class="col-sm-3">
            <select id="Region" class="form-control " name="Region" title="请选择市">
                <option selected>请选择县区</option>
            </select>
        </div>
    </div>

    <div class="form-group">
        <label class="col-sm-2 control-label">详细地址：</label>
        <div class="col-sm-10">
            @Html.TextBoxFor(p => p.Address, new { @class = "form-control", @placeholder = "请输入详细地址", maxlength = 50, })
        </div>

    </div>

    <div class="form-group">
        <label class="col-sm-2 control-label"><span class="red-600">*</span>联系人：</label>
        <div class="col-sm-4">
            @Html.TextBoxFor(p => p.Contacts, new { @class = "form-control", @placeholder = "请输入联系人", maxlength = 10, })
        </div>
        <label class="col-sm-2 control-label"><span class="red-600">*</span>手机号：</label>
        <div class="col-sm-4">
            @Html.TextBoxFor(p => p.ContactMobile, new { @class = "form-control", @placeholder = "请输入手机号", maxlength = 11, id = "ContactMobile" })
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label">电话：</label>
        <div class="col-sm-4">
            @Html.TextBoxFor(p => p.ContactsTel, new { @class = "form-control", @placeholder = "如：0511-4405222、021-87888822", maxlength = 13 })
        </div>
        <label class="col-sm-2 control-label">邮箱：</label>
        <div class="col-sm-4">
            @Html.TextBoxFor(p => p.Email, new { @class = "form-control", @placeholder = "请输入邮箱", maxlength = 30 })
        </div>
    </div>

    <div class="form-group">
        <label class="col-sm-2 control-label">是否公开：</label>
        <div class="col-sm-4">
            <input id="f1" type="radio" name="IsPublic" value=" " />
            <label for="f1">否</label>
            <input id="y1" type="radio" name="IsPublic" value=" " />
            <label for="y1">是</label>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label">证照图片：</label>
        <div class="col-xs-10 col-sm-10 col-md-10 col-lg-10">
            <div id="thelist" class="uploader-list" style="display:flex;align-items:center">
                <div id="picker" style="background: url('/Content/webImgs/upLogo/cp_img_tj.png'); width: 91px; height: 91px; border-radius: 5px;" class="webuploader-container">
                    @*<div class="webuploader-pick">
                        </div><div id="rt_rt_1c19vfs7l8ev1o5ige51an886r7" style="position: absolute; top: 0px; left: 0px; width: 91px; height: 91px; overflow: hidden; bottom: auto; right: auto;"><input type="file" name="file" class="webuploader-element-invisible" accept="image/jpg,image/jpeg,image/png"><label style="opacity: 0; width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);"></label></div>*@
                </div>
                <span>（建议上传200*60的图片）</span>
                <input type="hidden" id="CredentialImg" name="CredentialImg" value="@Model.CredentialImg" />
            </div>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label">备注：</label>
        <div class="col-sm-10">
            @Html.TextBoxFor(p => p.Remark, new { @class = "form-control" })
        </div>
    </div>

    <input id="IsCrossArea" value="@Model.IsCrossArea" type="hidden" />
    @*<input id="Sequence" name="Sequence" value="@Model.IsCrossArea" type="hidden" />*@


</form>
<script>
    function isSelectAll() {
      
        if ($('.dropdown-menu.inner li.selected').length>=20)
        {
            $('button[data-id="JurisdictionCity"]').attr('disabled', 'disabled');
            $('button[data-id="JurisdictionRegion"]').attr('disabled', 'disabled');
        }
        else {
            $('button[data-id="JurisdictionCity"]').removeAttr('disabled');
            $('button[data-id="JurisdictionRegion"]').removeAttr('disabled');
        }
    }


    $(function () {
        if ($('#CredentialImg').val()!='')
        {
         
            $('#picker').css({ 'background': 'url("' + $('#CredentialImg').val() + '")', 'backgroundSize': '100% 100%' });
        $('#picker').mouseenter(function () {
                $(this).css('background', 'url("/Content/webImgs/upLogo/cp_img_tj_a.png")');
            }).mouseleave(function () {
                $(this).css({ 'background': 'url("' + $('#CredentialImg').val() + '")', 'backgroundSize': '100% 100%' });
            });
        }
        else {
       
            $('#picker').mouseenter(function () {
            $(this).css('background', 'url("/Content/webImgs/upLogo/cp_img_tj_a.png")');
        }).mouseleave(function () {
            $(this).css('background', 'url("/Content/webImgs/upLogo/cp_img_tj.png")');
        });
        }
        var uploader = WebUploader.create({
            // swf文件路径
            //        swf: BASE_URL + '/js/Uploader.swf',
            //指定拖拽容器
            dnd: '#thelist',
            //截图可粘贴区域
            paste: 'document.body',

            // 文件接收服务端。
            server: '/DBH/UploadImgToOSS',

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: {
                id: '#picker',
                multiple: false
            },
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/jpg,image/jpeg,image/png'
            },

            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            resize: false
        });
        // 当有文件添加进来的时候
        uploader.on('fileQueued', function (file) {
            var $li = $(
                            '<div  id="' + file.id + '" class="img-thumbnail">' +
                            '<img alt="null"/>' +
    //                        '<p class="info">' + file.name + '</p>' +
                            '</div>'
                    ),
                    $img = $li.find('img');
            // $list为容器jQuery实例
            $('#thelist').prepend($li);
            // 创建缩略图
            // 如果为非图片文件，可以不用调用此方法。
            // thumbnailWidth x thumbnailHeight 为 100 x 100
            uploader.makeThumb(file, function (error, src) {
                if (error) {
                    $img.replaceWith('<span>不能预览</span>');
                    return;
                }
                $img.attr('src', src);
            }, 91, 91);
            $('#thelist > .img-thumbnail').eq(0).mouseenter(function () {
                var url = $(this).find('img').attr('src');
                $(this).attr('name', url).find('img').attr('src', '/Content/webImgs/upLogo/cp_img_sc.png');
            }).mouseleave(function () {
                var url = $(this).attr('name');
                $(this).find('img').attr('src', url);
            }).click(function () {
                $(this).remove();
                $('#picker').css('display', 'inline-block');
            });

            $('#picker').css('display', 'none');
            uploader.upload();
        });
        // 文件上传过程中创建进度条实时显示。
        uploader.on('uploadProgress', function (file, percentage) {
            var $li = $('#' + file.id), $percent = $li.find('.progress span');
            // 避免重复创建
            if (!$percent.length) {
                $percent = $('<p class="progress"><span></span></p>')
                        .appendTo($li)
                        .find('span');
            }
            $percent.css('width', percentage * 100 + '%');
        });

        // 文件上传成功，给item添加成功class, 用样式标记上传成功。
        uploader.on('uploadSuccess', function (file, response) {
            $('#CredentialImg').val(response._raw);
            $.L.msgSuccess('上传图片成功！');
        });

        // 文件上传失败，显示上传出错。
        uploader.on('uploadError', function (file) {
            var $li = $('#' + file.id),
                    $error = $li.find('div.error');
            // 避免重复创建
            if (!$error.length) {
                $error = $('<div class="error" style="position: relative"></div>').appendTo($li);
            }
            $error.text('上传失败');
            $error.append($('<span class="glyphicon glyphicon-remove" style="position: absolute;right: 0;color: green;font-size: 18px"></span>'))
        });

        // 完成上传完了，成功或者失败，先删除进度条。
        uploader.on('uploadComplete', function (file) {
            $('#' + file.id).find('.progress').remove();
        });
    });
    //初始化页面
    OnChanges();
    Privance1("Province", "@Model.Province");
    Distributor(@Model.ParentId);
   
    //获取经销商信息
    function Distributor(disId) {
         var selfDisId = "@Model.Id";
        $("#ParentId").empty();
        var SaleAreaId = $("#SaleAreaId").val();
        $.ajax({
            type: "POST",
            url: "Manager/SelDistributorList",
            data: { SaleAreaId: $("#SaleAreaId").val(), disId: disId, selfDisId: selfDisId },
            success: function (data) {
                $.each(data, function (i, item) {
                    if (item["Selected"] == true) {
                        $("<option></option>").val(item["Value"]).text(item["Text"]).attr("selected", "selected").appendTo($("#ParentId"))
                    }
                    else $("<option></option>").val(item["Value"]).text(item["Text"]).appendTo($("#ParentId"));
                })
            }
        });
    }
    //获取经销商等级
    function GetDistributorLevel(levelId) {
        $("#LevelID").empty();
        $.ajax({
            type: "POST",
            url: "Manager/SelDiscLevelList",
            data: { DistributorId: $("#ParentId").val(), levelId: levelId },
            success: function (data) {
                $.each(data, function (i, item) {
                    if (item["Selected"] == true) {
                        $("<option></option>").val(item["Value"]).text(item["Text"]).attr("selected", "selected").appendTo($("#LevelID"))
                    }
                    else $("<option></option>").val(item["Value"]).text(item["Text"]).appendTo($("#LevelID"));
                })
            }
        });
    }
    //获取所在地下拉列表
    function Privance1(BigPlaceId, ids) {
        $.ajax({
            type: "POST",
            url: "Manager/Privance?id=0" + "&ids=" + ids ,
            success: function (data) {
                var htmlsel = '';
                $("#" + BigPlaceId).children().remove();
                $.each(data, function (i, item) {
                    if (item.Selected) {
                        htmlsel += "<option  selected value='" + item.Value + "'>" + item.Text + "</option>";
                    }
                    else {
                        htmlsel += "<option  value='" + item.Value + "'>" + item.Text + "</option>";
                    }
                });
                $("#" + BigPlaceId).append(htmlsel);
                if (BigPlaceId == "Province") {
                    Choose1('Province', 'City', "@Model.City");
                }
            }
        })
    }
    function OnChanges() {
        GetDistributorLevel(@Model.LevelID);
        Privance("JurisdictionPrivance", "@Model.JurisdictionPrivance");
        Privance("AcrossPrivance", "@Model.AcrossPrivance");
    };
    //获取管辖区域和跨区域下拉列表
    function Privance(BigPlaceId, ids) {
        $.ajax({
            type: "POST",
            url: "Manager/GetPrivance?id=0" + "&ids=" + ids + "&DisId=" + $("#ParentId").val(),
            success: function (data) {
                var htmlsel = '';
                $("#" + BigPlaceId).children().remove();
                $.each(data, function (i, item) {
                    if (item.Selected) {
                        htmlsel += "<option  selected value='" + item.Value + "'>" + item.Text + "</option>";
                    }
                    else {
                        htmlsel += "<option  value='" + item.Value + "'>" + item.Text + "</option>";
                    }
                });
                $("#" + BigPlaceId).attr('multiple', 'multiple').append(htmlsel);
                $("#" + BigPlaceId).selectpicker();
                $("#" + BigPlaceId).selectpicker('refresh');
                if (BigPlaceId == "JurisdictionPrivance") {

                    Choose('JurisdictionPrivance', 'JurisdictionCity', "@Model.JurisdictionCity",1,0)
                } if (BigPlaceId == "AcrossPrivance") {

                    Choose('AcrossPrivance', 'AcrossCity', "@Model.AcrossCity",1,1)
                }
                @*if (BigPlaceId == "Province") {

                    Choose('Province', 'City', "@Model.City",0);
                }*@
            }
        });

    }

    function Choose1(BigPlaceId, SmallPlaceId, ids) {
        var id = $("#" + BigPlaceId).val();
        $.ajax({
            type: "POST",
            url: "Manager/Privance?id=" + id + "&ids=" + ids,
            success: function (response) {

                var htmlsel = '';
                $("#" + SmallPlaceId).children().remove();
                $.each(response, function (i, item) {
                    if (item.Selected) {
                        htmlsel += "<option  selected value='" + item.Value + "'>" + item.Text + "</option>";
                    }
                    else {
                      
                        htmlsel += "<option  value='" + item.Value + "'>" + item.Text + "</option>";
                    }

                });
                $("#" + SmallPlaceId).append(htmlsel);
                if (SmallPlaceId == "City") {
                    Choose1('City', 'Region', "@Model.Region");
                }
            }
        });

    }
    //type:1 市级数据的加载 2 区/县数据的加载
    //acrossType: 0 管辖区域下拉框数据的加载 1 跨片区下拉框加载
    function Choose(BigPlaceId, SmallPlaceId, ids, type, acrossType) {
        var id = $("#" + BigPlaceId).val();
        $.ajax({
            type: "POST",
            url: "Manager/GetPrivance?id=" + id + "&ids=" + ids + "&DisId=" + $("#ParentId").val() + "&type=" + type + "&acrossType=" + acrossType,
            success: function (response) {
                var htmlsel = '';
                $("#" + SmallPlaceId).children().remove();
                $.each(response, function (i, item) {
                    if (item.Selected) {
                        htmlsel += "<option  selected value='" + item.Value + "'>" + item.Text + "</option>";
                    }
                    else {
                        htmlsel += "<option  value='" + item.Value + "'>" + item.Text + "</option>";
                    }

                });
                $("#" + SmallPlaceId).attr('multiple', 'multiple').append(htmlsel);
                $("#" + SmallPlaceId).selectpicker({});
                $("#" + SmallPlaceId).selectpicker('refresh');
                if (SmallPlaceId == "JurisdictionCity") {
                    Choose('JurisdictionCity', 'JurisdictionRegion', "@Model.JurisdictionRegion",2,0)
                } if (SmallPlaceId == "AcrossCity") {

                    Choose('AcrossCity', 'AcrossRegion', "@Model.AcrossRegion",2,1)
                }
                @*if (SmallPlaceId == "City") {

                    Choose('City', 'Region', "@Model.Region",0)
                }*@
            }
        });


    }

    $(function () {
        //初始化
        var IsCrossArea = $("#IsCrossArea").val();
        if (IsCrossArea == null) IsCrossArea = 0;
        if (IsCrossArea == 0) {
            $('input[type="radio"][name="IsCrossArea"][value="0"]').attr('checked', true);
            $(" #cross").css('display', 'none');
        }
        else {
            $('input[type="radio"][name="IsCrossArea"][value="1"]').attr('checked', true);
            $(" #cross").css('display', 'block');
        }
        //选择改变后 //change  值变了之后才执行
        $('input[type="radio"][name="IsCrossArea"]').change(function () {
            if ($(this).val() == 0) {
                $(" #cross.form-group").css('display', 'none');
            }
            else {
                $(" #cross.form-group").css('display', 'block');
            }
        })
    })
    $(function () {
        $('#form').bootstrapValidator({
            group: '.col-sm-4',
            fields: {
                Name: {
                    validators: {
                        notEmpty: {
                            message: '经销商名称不能为空'
                        },
                        stringLength: {
                            max: 25,
                            message: '经销商名称最大长度为25'
                        },
                        //regexp: {
                        //    regexp: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/,
                        //    message: '经销商名称不能输入符号'
                        //},

                    }
                },
                LevelID: {
                    validators: {
                        notEmpty: {
                            message: '经销商级别不能为空'
                        },

                    }
                },
                Contacts: {
                    validators: {
                        notEmpty: {
                            message: '联系人不能为空'
                        },
                        stringLength: {
                            max: 20,
                            message: '联系人最大长度为20'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/,
                            message: '联系人不能输入符号'
                        }
                    }
                },
                ContactMobile: {
                    validators: {
                        notEmpty: {
                            message: '手机号不能为空'
                        },
                        regexp: {
                            regexp: /^1[0-9]{10}$/,
                            message: '手机号码格式错误'
                        }
                    }
                },
                Address: {
                    validators: {
                        stringLength: {
                            max: 50,
                            message: '详细地址最大长度为50',
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/,
                            message: '详细地址不能输入符号'
                        }
                    }
                },
                Email: {
                    validators: {
                        emailAddress: {
                            message: '邮箱地址格式有误'
                        }
                    },
                },
                ContactsTel: {
                    validators: {
                        regexp: {
                            regexp: /^0\d{2,3}-\d{6,8}$/,
                            message: '电话号码格式错误'
                        }
                    }
                }
            }
        })
        var NameValue = $("input[name='Name']").val();
        var ContactMobileValue = $("input[name='ContactMobile']").val();

        $("input[name='Name']").on("change", function () {
            if ($("input[name='Name']").val() != NameValue) {
                $('#form').bootstrapValidator("addField", "Name", {//添加验证
                    validators: {
                        threshold: 1, //有6字符以上才发送ajax请求，（input中输入一个字符，插件会向服务器发送一次，设置限制，6字符以上才开始）
                        remote: {//ajax验证。server result:{"valid",true or false} 向服务发送当前input name值，获得一个json数据。例表示正确：{"valid",true}
                            type: "post",
                            data: { id: '@Model.Id' },
                            url: "/Manager/CheckDealerName",
                            message: '经销商名称不能重复',
                            //delay: 2000
                        }
                    }
                })
            }
            else {
                var bootstrapValidator = $("#form").data('bootstrapValidator').validate() //触发全部验证
                $('#form').bootstrapValidator('removeField', 'Name');//去除验证
            }
            $('#form').bootstrapValidator('validate');
            var bv = $('#form').data("bootstrapValidator")
            var bool = bv.isValid();
        })

        $("input[name='ContactMobile']").on("change", function () {
        
            if ($("input[name='ContactMobile']").val() != ContactMobileValue) {

                $('#form').bootstrapValidator("addField", "ContactMobile", {//添加验证
                    validators: {
                        threshold: 1, //有6字符以上才发送ajax请求，（input中输入一个字符，插件会向服务器发送一次，设置限制，6字符以上才开始）
                        remote: {//ajax验证。server result:{"valid",true or false} 向服务发送当前input name值，获得一个json数据。例表示正确：{"valid",true}
                            type: "post",
                            data: { id: '@Model.Id' },
                            url: "/Manager/CheckDealerName",
                            message: '此手机号已存在',
                            //delay: 2000
                        }
                    }
                });
            } else {
                $('#form').bootstrapValidator('removeField', 'ContactMobile');//去除验证
            }
            $('#form').bootstrapValidator('validate');
            var bv = $('#form').data("bootstrapValidator")
            var bool = bv.isValid();
        })
    })
</script>
